using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiWrite.Application.Command;

namespace WMS.WebApiWrite.Application.Commandhandler
{
    /// <summary>
    /// 新增产品信息命令处理器
    /// </summary>
    public class AddProductCommandHandler : IRequestHandler<AddProductCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<ProductInfo> productRepository;
        private static readonly Random random = new Random();

        /// <summary>
        /// 构造函数，注入产品仓储
        /// </summary>
        public AddProductCommandHandler(IBaseRepository<ProductInfo> productRepository)
        {
            this.productRepository = productRepository;
        }

        /// <summary>
        /// 处理新增产品信息命令
        /// </summary>
        public async Task<ApiResult<bool>> Handle(AddProductCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 自动生成唯一的货品编号（格式：HPDH+4位随机数）
                var productCode = GenerateUniqueProductCode();

                // 创建产品信息实体
                var productInfo = new ProductInfo
                {
                    ProductCode = productCode, // 使用自动生成的编码
                    ProductName = request.ProductDTO.ProductName,
                    SpecificationModel = request.ProductDTO.SpecificationModel,
                    Unit = request.ProductDTO.Unit,
                    InboundUnitPrice = request.ProductDTO.InboundUnitPrice,
                    CurrentInventory = request.ProductDTO.CurrentInventory,
                    WarehouseId = request.ProductDTO.WarehouseId,
                    IsDeleted = false, // 新建数据默认未删除
                    DataStatus = request.ProductDTO.DataStatus, // 数据状态：1草稿 2已提交
                    CreateName = request.ProductDTO.OperatorName,
                    CreateTime = DateTime.Now
                };

                // 执行新增操作
                var result = await productRepository.AddAsync(productInfo);

                if (result > 0)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiResultEnum.新增成功,
                        Message = request.ProductDTO.DataStatus == 1 ? "保存草稿成功" : "新增产品信息成功",
                        Data = true
                    };
                }
                else
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiResultEnum.新增失败,
                        Message = "新增产品信息失败",
                        Data = false
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiResultEnum.新增失败,
                    Message = $"新增产品信息异常：{ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 生成唯一的货品编号（格式：HPDH+4位随机数，如：HPDH1234）
        /// </summary>
        private string GenerateUniqueProductCode()
        {
            string code;
            int maxAttempts = 100; // 最大尝试次数
            int attempts = 0;

            do
            {
                // 生成4位随机数：1000-9999
                int randomNumber = random.Next(1000, 10000);
                code = $"HPDH{randomNumber}"; // 例如：HPDH1234

                attempts++;
                if (attempts >= maxAttempts)
                {
                    // 如果尝试多次仍重复，使用时分秒替代随机数
                    string timePart = DateTime.Now.ToString("HHmmss");
                    code = $"HPDH{timePart}";
                    break;
                }
            } while (productRepository.GetAll().Where(x => !x.IsDeleted).Any(x => x.ProductCode == code)); // 只检查未删除的记录

            return code;
        }
    }
}

